package cloud.shyidong.admin.tenant.service;

import cloud.shyidong.core.request.LongIdRequest;
import cloud.shyidong.core.service.AbstractService;
import cloud.shyidong.core.util.ObjectUtils;
import cloud.shyidong.tenant.dao.TenantMenuDao;
import cloud.shyidong.tenant.entity.TenantMenuEntity;
import cloud.shyidong.tenant.request.TenantMenuInsertRequest;
import cloud.shyidong.tenant.request.TenantMenuPageRequest;
import cloud.shyidong.tenant.request.TenantMenuUpdateRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 租户菜单业务处理
 * </p>
 *
 * @author syd
 * @since 2023-09-18 15:34:25
 */
@Service
public class TenantMenuService extends AbstractService<TenantMenuDao, TenantMenuEntity, LongIdRequest, TenantMenuInsertRequest, TenantMenuUpdateRequest, TenantMenuPageRequest> {
    
    @Override
    public Map<String, Object> view(LongIdRequest idRequest) {
        Map<String, Object> result = super.view(idRequest);
        if (result.containsKey("parentId")) {
            Long parentId = (Long) result.get("parentId");
            if (ObjectUtils.isNotNull(parentId) && parentId > 0) {
                TenantMenuEntity tenantMenuEntity = getDao().selectById(parentId);
                result.put("parentName", tenantMenuEntity.getName());
            }
        }
        return result;
    }
    
    @Override
    public List<TenantMenuEntity> search(TenantMenuPageRequest pageRequest) {
        List<TenantMenuEntity> result = new ArrayList<>();
        List<TenantMenuEntity> tenantMenuEntities = super.search(pageRequest);
        Map<Long, TenantMenuEntity> tenantMenuEntityMap = tenantMenuEntities.stream().collect(Collectors.toMap(TenantMenuEntity::getId, tenantMenuEntity -> tenantMenuEntity));
        for (TenantMenuEntity tenantMenuEntity : tenantMenuEntities) {
            if (ObjectUtils.isNull(tenantMenuEntity.getParentId())) {
                result.add(tenantMenuEntity);
            } else {
                TenantMenuEntity parentMenuEntity = tenantMenuEntityMap.get(tenantMenuEntity.getParentId());
                if (ObjectUtils.isNull(parentMenuEntity)) {
                    result.add(tenantMenuEntity);
                } else {
                    parentMenuEntity.getTreeList().add(tenantMenuEntity);
                }
            }
        }
        return result;
    }
    
}
